<h1><?php echo $this->pageTitle; ?></h1>
<?php echo $ajax->form('CustStockInHead', 'post', array('id' => 'formMain', 'update'=>'content', 'indicator' => 'indicator', 'url'=>array('action'=>'save')));?>
<div class="toolbar">
    <div id="tLeft">
        <?php if ($from_supplier == true) {
            $this->requestAction('cust_stocks_in/supplier_read_only/0');
        } ?>
        <?php if ($mode == 'add') : ?>
            <?php echo $this->element('toolbar', array('buttons' => array('save', 'clear', 'back'))); ?>
        <?php else : // mode edit ?>
            <?php echo $this->element('toolbar', array('buttons' => array('add', array('print' => array('model' => 'CustStockInHead')), 'back'))); ?>
        <?php endif; ?>
        <?php if ($from_supplier == true) {
            $this->requestAction('cust_stocks_in/supplier_read_only/1');
        } ?>
    </div>
    <div id="tRight"><?php echo $this->element('neighbors', array('model' => 'CustStockInHead', 'title' => 'stock_in_no')); ?></div>
</div>

<?php echo $form->input('CustStockInHead.id'); ?>
<fieldset>
    <table>
        <tr>
            <td width="150px"><?php echo $form->label('CustStockInHead.stock_in_date', 'Stock in date'); ?></td>
            <td width="250px">
                <?php if($mode == 'add') : ?>
                    <?php echo $html->tag('span', $today); ?>
                    <?php echo $form->hidden('CustStockInHead.stock_in_date', array('id' => 'stock_in_date', 'value' => $today)); ?>
                <?php else : ?>
                    <?php echo $html->tag('span', $this->data['CustStockInHead']['stock_in_date']); ?>
                <?php endif; ?>
            </td>
            <?php if($mode == 'add' && $from_supplier == false) : ?>
            <td width="180px"><?php echo $form->label('CustStockInHead.dispatch_from', 'Dispatch from', array('class' => 'required')); ?></td>
            <td>
                    <?php echo $form->radio('CustStockInHead.dispatch_from', array(ITS_PREFIX => 'ITS', SUPPLIER_PREFIX => 'Other Vendor'), array('legend' => false)); ?><br />
            </td>
            <?php else : ?>
            <td width="180px"><?php echo $form->label('CustStockInHead.dispatch_from', 'Vendor'); ?></td>
            <td>
                    <?php if ($from_supplier == true) : ?>
                        <?php echo $supplierName; ?>
                        <?php echo $form->hidden('CustStockInHead.supplier_id', array('value' => $session->read('Auth.User.supplier_id'))); ?>
                    <?php else: ?>
                        <?php echo $this->data['CustStockInHead']['dispatch_from'] == ITS_PREFIX? $this->requestAction('system_preferences/get/company_name') : $this->data['Supplier']['name']; ?>
                    <?php endif; ?>
            </td>
            <?php endif; ?>
        </tr>
        <tr>
            <td><?php echo $form->label('CustStockInHead.stock_in_no', 'Stock in no'); ?></td>
            <td>
                <?php if($mode == 'add') : ?>
                <?php else : ?>
                    <?php echo $html->tag('span', $this->data['CustStockInHead']['stock_in_no']); ?>
                <?php endif; ?>
            </td>
            <td width="180px"><?php echo $form->label('CustStockInHead.dispatch_id', 'Ref. by dispatch no', array('class' => 'required')); ?></td>
            <td>
                <?php if($mode == 'add') : ?>
                    <?php echo $form->hidden('CustStockInHead.dispatch_id', array('id' => 'hidCustStockInHeadDispatchId')); ?>
                    <?php echo $form->select('CustStockInHead.supplier_dispatch_id', $supplierDispatches, null, array('style' => 'display: none;')); ?>
                    <?php if ($from_supplier == true) : ?>
                <input type="radio" value="supplier" checked="checked" class="hide" />
                <input type="hidden" value="supplier" name="data[CustStockInHead][dispatch_from]" class="hide" />
                    <?php else: ?>
                        <?php echo $form->select('CustStockInHead.dispatch_id', $dispatches, null, array('style' => 'display: none;')); ?>
                    <?php endif; ?>
                <?php else : ?>
                    <?php echo $this->data['CustStockInHead']['dispatch_from'] == ITS_PREFIX? $this->data['Dispatch']['dispatch_no']: $this->data['SDH']['dispatch_no']; ?>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <td><?php echo $form->label('CustStockInHead.stock_in_by', 'Stock in by'); ?></td>
            <td>
                <?php if($mode == 'add') : ?>
                    <?php echo $html->tag('span', $stock_in_by); ?>
                    <?php echo $form->hidden('CustStockInHead.stock_in_by', array('value' => $stock_in_by)); ?>
                <?php else : ?>
                    <?php echo $html->tag('span', $this->data['CustStockInHead']['stock_in_by']); ?>
                <?php endif; ?>
            </td>
            <?php if($mode == 'add' && $from_supplier == false) : ?>
            <td><?php echo $form->label(null, 'Vendor'); ?></td>
            <td>
                    <?php echo $form->hidden('CustStockInHead.supplier_id'); ?>
                <span id="CustStockInHeadVendor" style="display: none;"></span>
                <span id="CustStockInHeadVendorITS" style="display: none;"><?php echo $this->requestAction('system_preferences/get/company_name'); ?></span>
            </td>
            <?php else : ?>
            <td>&nbsp;</td><td>&nbsp;</td>
            <?php endif; ?>
        </tr>
    </table>
</fieldset>

<fieldset>
    <table class="data">
        <thead>
            <tr>
                <th width="35px">No</th>
                <th width="135px">Part no.</th>
                <th width="120px">Stock code</th>
                <th>Description</th>
                <?php if($mode == 'add') : ?>
                <th width="120px">Location</th>
                <?php endif; ?>
                <th width="<?php echo $mode == 'add'? '120' : '50'; ?>px">Qty</th>
                <th width="50px">Unit</th>
                <?php if($mode == 'edit') : ?>
                <th width="60px">Index</th>
                <?php endif; ?>
                <?php if($mode == 'add') : ?>
                <th class="action">&nbsp;</th>
                <?php endif; ?>
            </tr>
        </thead>
        <tbody id="productRow">
            <?php if ($mode == 'add') : ?>
            <?php else : $count = count($this->data['CustStockIn'])// mode edit ?>
                <?php for($i = 0; $i < $count; ++$i) : ?>
            <tr class="<?php echo (($i + 1) % 2 == 0)? 'even-cell' : 'odd-cell'; ?>">
                <td><span><?php echo $i + 1; ?></span></td>
                <td>
                            <?php echo $html->link($this->data['CustStockInHead']['dispatch_from'] == ITS_PREFIX? $this->data['CustStockIn'][$i]['Product']['part_no']: $this->data['CustStockIn'][$i]['Product']['supplier_part_no'],
                            '/cust_product_sites/view/' . $this->data['CustStockIn'][$i]['cust_product_site_id'] . '/' . strtotime('now'),
                            array('target' => '_blank')); ?>
                </td>
                <td class="center"><?php echo $this->data['CustStockIn'][$i]['CustProductSite']['stock_code']; ?></td>
                <td>
                            <?php echo !empty($this->data['CustStockIn'][$i]['CustProductSite']['text'])?
                            $this->data['CustStockIn'][$i]['CustProductSite']['text']:
                            $this->data['CustStockIn'][$i]['Product']['text']; ?>
                </td>
                <td class="text-right"><?php echo $this->data['CustStockIn'][$i]['stock_in_qty']; ?></td>
                <td class="center">
                            <?php echo $this->data['CustStockIn'][$i]['Product']['Unit']['title']; ?>
                </td>
                <td class="center">
                            <?php echo $ajax->link($html->image('icon/popup.png', array('alt' => 'Index information')),
                            array('controller' => 'products_serials', 'action' => 'popup_cust_view', $this->data['CustStockIn'][$i]['product_id'] . '/' . 'cust_stock_in_id:' . $this->data['CustStockIn'][$i]['id'] . '/cust_stock_in_type:' . CustStockIn::CUST_STOCK_IN_TYPE),
                            array('update' => 'content', 'position' => 'bottom', 'indicator' => 'indicator' ), null, false); ?>
                </td>
            </tr>
                <?php endfor; ?>
            <?php endif; ?>
        </tbody>
    </table>
</fieldset>

<?php echo $form->end(); ?>
<?php if ($mode == 'add') : ?>
<script type="text/javascript">
    // JSON เก็บ part no ที่ป้อนเข้ามา อ้างไปยังลำดับแถว
    var partNos = {};

    requestCustStockIn = function(event) {
        var e = $j(event.target);
        var no = e.attr("no");  // ลำดับแถวปัจจุบัน เริ่มที่ 0
        var part_no = $j.trim(e.val());  // part no ที่ใส่เข้ามา

        // ไม่ได้ใส่อะไรเข้ามา
        if(part_no.length == 0) { return; }

        // ถ้ายังไม่มี part no นี้อยู่ ไปดึงข้อมูลจาก Server
        if (partNos[part_no] == null) {
            var dispatch_from = $j(':radio:checked').val();
            if (dispatch_from == 'its') {
                var dispatch_id = $j("#CustStockInHeadDispatchId").val();

                if (dispatch_id == "") {
                    alert("Please select a Dispatch no");
                    $j('#CustStockIn' + no + 'PartNo').val('');
                    return;
                }

                var url = base + "/cust_stocks_in/json_find_by_part_no_dispatch_id/";
                var params = {part_no: part_no, dispatch_id: dispatch_id};

            } else { // supplier
                var dispatch_id = $j("#CustStockInHeadSupplierDispatchId").val();

                if (dispatch_id == "") {
                    alert("Please select a Vendor Dispatch no");
                    $j('#CustStockIn' + no + 'PartNo').val('');
                    return;
                }

                var url = base + "/cust_stocks_in/json_find_by_part_no_supplier_dispatch_id/";
                var params = {part_no: part_no, dispatch_id: dispatch_id};
            }

            // ปิดไม่ให้เลือก dispat from / no ใหม่
            $j("#CustStockInHeadSupplierDispatchId").attr('disabled', true);
            $j("#CustStockInHeadDispatchId").attr('disabled', true);
            $j("#CustStockInHeadDispatchFrom_").val(dispatch_from);
            $j(":radio").attr('disabled', true);
            postRequest(url, params, function(data) {
                // พบข้อมูล
                if (data) {
                } else { // ไม่พบข้อมูล (กรอกข้อมูลผิด...)
                    e.val('');
                    alert("No product found.");
                    return;
                }
                // set ค่ารายการตามประเภท dispatch
                var line = dispatch_from == 'its'? data.CustStockIn: data.SD;

                if (dispatch_from == 'its') {
                    $j("#CustStockIn" + no + "Id").val(line.id);
                }
                $("CustStockIn" + no + "PartNo").hide();
                $("CustStockIn" + no + "PartNoSpan").update(dispatch_from == ITS_PREFIX? data.Product.part_no: data.Product.supplier_part_no);
                $("CustStockIn" + no + "PartNoSpan").show();
                $("CustStockIn" + no + "StockCode").update(data.CustProductSite.stock_code);
                $("CustStockIn" + no + "CustProductSiteId").value = line.cust_product_site_id;
                $("CustStockIn" + no + "ProductText").update(data.Product.text);
                $("CustStockIn" + no + "ProductText").update(data.CustProductSite.text != null? data.CustProductSite.text: data.Product.text);
                $("CustStockIn" + no + "ProductId").value = line.product_id;
                $("CustStockIn" + no + "ItsStockOutId").value = line.id;
                $("CustStockIn" + no + "DeliverQty").update("/" + (dispatch_from == 'its'? line.deliver_qty: line.qty));
                $("CustStockIn" + no + "ProductUnitTitle").update(data.Product.Unit.title);
                $("CustStockIn" + no + "StockInQty").value = 1;


                requestOptions("cust_locations", "CustStockIn" + no + "CustProductSiteId", "CustStockIn" + no + "CustLocationId", true, 'option_cps_location_list');
//                $j("#CustStockIn" + no + "CustLocationId").bind('change', function(event) {
//                    selectStockInLocation(no);
//                }).after($j('<div id="CustStockIn' + no + 'SeeIndex" class="caption" style="display: none;">(See index)</div>'));

                // ดักจับ Event กดลบแถว
                $j('#linkCustStockIn' + no + 'Delete').bind('click', function() {
                    // ลบรายการ part no ออกจาก list
                    var p = $j("#CustStockIn" + no + "PartNoSpan").text();
                    var sc = $j("#CustStockIn" + no + "StockCode").text();
                    partNos[p] = undefined;
                    partNos[sc] = undefined;

                    // ลบ แถว
                    $j('#CustStockIn' + no + 'Id').parents('tr').remove();

                    // จัดลำดับตัวเลขหน้าแถวใหม่
                    $j('#productRow').runno();
                }).show();

                // บันทึกแถวปัจจุบันของ part no
                partNos[data.Product.part_no] = no;
                partNos[data.Product.supplier_part_no] = no;
                partNos[data.CustProductSite.stock_code] = no;
                var nextRow = (parseInt(no) + 1);
                createRow(nextRow)
                $("CustStockIn" + nextRow + "PartNo").focus();

//                if (dispatch_from == 'its') {
//                    requestProductSerial(no, data.CustStockIn.id, 'S');
//                } else {
//                    requestProductSerial(no, data.SD.id, 'SD');
//                }
            }
        );
        } else {
            e.val('');
            var row = partNos[part_no]; // แถวที่มี part_no นี้อยู่
            $j("#CustStockIn" + row + "StockInQty").val(parseInt($j("#CustStockIn" + row + "StockInQty").val()) + 1);
            setTimeout(function() {
                $("CustStockIn" + no + "PartNo").focus();
            }, 100);
            checkStockInQty(row);
        }
    }
    /**
     * นับจำนวน stock in qty ว่าเกินกว่าที่ส่งหรือไม่
     */
    checkStockInQty = function(no) {
        var deliverQty = parseInt($("CustStockIn" + no + "DeliverQty").innerHTML.substring(1)) // innerHTML = "/[DeliverQty]"
        var stockInQty = parseInt($F("CustStockIn" + no + "StockInQty"))
        if (stockInQty > deliverQty) {
            alert("Please stock in quantity less than deliver quantity")
            $("CustStockIn" + no + "StockInQty").value = deliverQty;
            stockInQty = deliverQty;
        }
        var stocksIn = $j("#Index" + no + " :checkbox").attr('checked', false).slice(0, stockInQty);
        // ถ้าเป็น IE 6 ต้องใช้ defaultChecked เพิ่มถึงจะ ติ๊กถูกให้จริง ๆ
        if ($j.browser.msie && ($j.browser.version == 6)) {
            stocksIn.attr('defaultChecked', true);
        } else {
            stocksIn.attr('checked', true);
        }

        $j('table.data tr:not(:has(:checked))').removeClass('selected');
        $j('table.index tr:has(:checked)').addClass('selected');
        selectStockInLocation(no);
    }

    function createRow(row) {
        var tBody = $("productRow");
        var tr = new Element("tr");
        tr.addClassName(((row + 1) % 2 == 0)? "even-cell" : "odd-cell");

        tr.update('<input id="CustStockIn' + row + 'Id" type="hidden" value="" name="data[CustStockIn][' + row + '][id]" />');

        var tdNo = new Element("td");
        tdNo.update('&nbsp;');
        tr.insert(tdNo);

        var tdPartNo = new Element("td");
        tdPartNo.insert('<input id="CustStockIn' + row + 'PartNo" type="text" value="" no="' + row + '" name="data[CustStockIn][' + row + '][part_no]"/>');
        tdPartNo.insert('<input id="CustStockIn' + row + 'ProductId" type="hidden" value="" name="data[CustStockIn][' + row + '][product_id]"/>');
        tdPartNo.insert('<input id="CustStockIn' + row + 'CustProductSiteId" type="hidden" value="" name="data[CustStockIn][' + row + '][cust_product_site_id]"/>');
        tdPartNo.insert('<input id="CustStockIn' + row + 'ItsStockOutId" type="hidden" value="" name="data[CustStockIn][' + row + '][its_stock_out_id]"/>');
        tdPartNo.insert('<span id="CustStockIn' + row + 'PartNoSpan" style="display: none"></span>');
        tr.insert(tdPartNo);

        var tdStockCode = new Element("td", {'class': 'center'});
        tdStockCode.insert('<span id="CustStockIn' + row + 'StockCode"></span>');
        tr.insert(tdStockCode);

        var tdTitle = new Element("td");
        tdTitle.insert('<span id="CustStockIn' + row + 'ProductText"></span>');
        tr.insert(tdTitle);

        var tdLocation = new Element("td", {id: "CustLocationTd" + row});
        tdLocation.insert('<select id="CustStockIn' + row + 'CustLocationId" + name="data[CustStockIn][' + row + '][cust_location_id]" no="' + row + '"></select>');
        tr.insert(tdLocation);

        var tdStockInQty = new Element("td");
        tdStockInQty.insert('<input id="CustStockIn' + row + 'StockInQty" no="' + row + '" class="text-right" type="text" value="" maxlength="3" size="3" name="data[CustStockIn][' + row + '][stock_in_qty]"/>');
        tdStockInQty.insert('<span id="CustStockIn' + row + 'DeliverQty"></span>');
        tr.insert(tdStockInQty);

        var tdUnit = new Element("td", {'class': 'center'});
        tdUnit.insert('<span id="CustStockIn' + row + 'ProductUnitTitle"></span>');
        tr.insert(tdUnit);

//        var tdIndex = new Element("td", {id: 'tdIndex' + row, "class": "center"});
//        tdIndex.insert('<a href="#" id="CustStockIn' + row + 'Index"><?php echo $html->image('icon/popup.png', array('title' => 'Index', 'alt' => 'Index')); ?><div id="Index' + row + '" style="display: none;"></div><div id="popupIndex' + row + '"></div>');
//        tr.insert(tdIndex);

        var tdDelete = new Element("td", {"class": "center"});
        tdDelete.insert('<a href="#" id="linkCustStockIn' + row + 'Delete" style="display: none;"><?php echo $html->image('icon/delete.png', array('title' => 'Delete', 'alt' => 'Delete')); ?></a>');
        tr.insert(tdDelete);

        tBody.insert(tr);
        $j('#productRow').runno();
        addRowListener(row);
    }

    function selectStockInLocation(row) {
        var location_id = $F("CustStockIn" + row + "CustLocationId");
        $j("tr select", "#Index" + row).val(location_id);
    };

    function addRowListener(row) {
        $j("#CustStockIn" + row + "PartNo").bind('keypress', partNoKeyPress);

        $j("#CustStockIn" + row + "PartNo").bind('blur', function(event) {
            requestCustStockIn(event);
        });

        $j("#CustStockIn" + row + "CustLocationId").bind('change', function(event) {
            selectStockInLocation(Event.element(event).readAttribute("no"));
        });

        $j("#CustStockIn" + row + "StockInQty").bind('keypress', stopKeyEnter);
        $j("#CustStockIn" + row + "StockInQty").bind('change', function(event) {
            checkStockInQty(Event.element(event).readAttribute("no"));
        });

//        $j("#CustStockIn" + row + "Index").bind('click', function(event) {
//            popupIndex(row);
//        });
//        initPopUpIndex(row);
    };

    $j(function() {
        // การเลือก send to ว่า Supplier / ITS
        $j(":radio[id*=DispatchFrom]").bind('click', function() {
            if ($j(this).is(':checked')) {
                var dispatch_from = $j(this).val();
            }
            $j('#CustStockInHeadDispatchId').hide();
            $j('#CustStockInHeadSupplierDispatchId').hide();
            $j('#CustStockInHeadVendorITS').hide();
            $j('#CustStockInHeadVendor').hide();
            if (dispatch_from == 'its') {
                $j('#CustStockInHeadDispatchId').show();
                $j('#CustStockInHeadVendorITS').show();
                $j('#CustStockInHeadSupplierDispatchId').val('');
                $j('#CustStockInHeadSupplierId').val('');
                $j('#CustStockInHeadVendor').text('');
                // ถ้าไม่มีรายการ Dispatch (option length == 1)
                if ($j('#CustStockInHeadDispatchId').children().length == 1) {
                    alert('There is no Dispatch from ITS sent to your site');
                }
            } else if (dispatch_from == 'supplier') {
                $j('#CustStockInHeadVendor').show();
                $j('#CustStockInHeadSupplierDispatchId').show();
                // ถ้าไม่มีรายการ Supplier Dispatch (option length == 1)
                if ($j('#CustStockInHeadSupplierDispatchId').children().length == 1) {
                    alert('There is no Vendor Dispatch sent to your site');
                }
            }
        });

    <?php if ($from_supplier != true) : ?>
            $j('#CustStockInHeadSupplierDispatchId').bind('change', function() {
                postRequest(base + '/cust_stocks_in/json_supplier_by_dispatch_id', {sdh_id: $j('#CustStockInHeadSupplierDispatchId').val()}, function (data) {
                    if (data != false) {
                        $j('#CustStockInHeadSupplierId').val(data.Supplier.id);
                        $j('#CustStockInHeadVendor').text(data.Supplier.name);
                    } else {
                        $j('#CustStockInHeadSupplierId').val('');
                        $j('#CustStockInHeadVendor').text('');
                    }
                });
            });
    <?php else:  ?>
            $j('#CustStockInHeadSupplierDispatchId').show();
    <?php endif; ?>
            // ดักจับ event การเลือก Dispatch, Supplier Dispatch คัดลอกค่าลง hidden
            $j('select[id^=CustStockInHead]').bind('change', function() {
                $j('#hidCustStockInHeadDispatchId').val($j(this).val());
            });
            createRow(0);
        })
</script>
<?php endif; ?>